package com.lantzuc.lanucbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lantzuc.lanucbackend.annotation.AuthCheck;
import com.lantzuc.lanucbackend.common.BaseResponse;
import com.lantzuc.lanucbackend.common.ErrorCode;
import com.lantzuc.lanucbackend.common.ResultUtils;
import com.lantzuc.lanucbackend.constant.UserConstant;
import com.lantzuc.lanucbackend.exception.BusinessException;
import com.lantzuc.lanucbackend.model.domain.User;
import com.lantzuc.lanucbackend.model.domain.request.LoginResponse;
import com.lantzuc.lanucbackend.model.domain.request.UseLoginRequest;
import com.lantzuc.lanucbackend.model.domain.request.UseRegisterRequest;
import com.lantzuc.lanucbackend.model.enums.UserRoleEnum;
import com.lantzuc.lanucbackend.service.UserService;
import com.lantzuc.lanucbackend.utils.JwtUtils;
import io.jsonwebtoken.Jwt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.lantzuc.lanucbackend.constant.UserConstant.ADMIN_ROLE;
import static com.lantzuc.lanucbackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * <p>Project: lanuc-backend
 * <p>Powered by Lantz On 2025/4/17
 *
 * @author Lantz
 * @version 1.0
 * @Description UserController
 * @since 1.8
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Long userRegister(@RequestBody UseRegisterRequest useRegisterRequest){
        if (useRegisterRequest == null){
            return null;
        }
        String userAccount = useRegisterRequest.getUserAccount();
        String userPassword = useRegisterRequest.getUserPassword();
        String checkPassword = useRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        return userService.userRegister(userAccount, userPassword, checkPassword);
    }

    @PostMapping("/login")
    public BaseResponse<LoginResponse> userLogin(@RequestBody UseLoginRequest useLoginRequest, HttpServletRequest request){
        if (useLoginRequest == null){
            return null;
        }
        String userAccount = useLoginRequest.getUserAccount();
        String userPassword = useLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        if (user == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "登录失败");
        }
        // 获取登录用户
        User loginUer = userService.getLoginUer(request);
        // 生成令牌，下发令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginUer.getId());
        claims.put("userAccount", loginUer.getUserAccount());
        claims.put("userName", loginUer.getUserName());
        String jwt = JwtUtils.generateToken(claims); // 生成令牌

        // 创建登录响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUser(user);
        loginResponse.setJwt(jwt);

        return ResultUtils.success(loginResponse);
    }

    @GetMapping("/current")
    public User getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            return null;
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        return userService.getSafetyUser(user);
    }


    @GetMapping("/search")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public List<User> searchUser(String userName, HttpServletRequest request){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("userName", userName);
        }
        List<User> userList = userService.list(queryWrapper);
        return userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
    }

    @PostMapping("/delete")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public boolean deleteUser(@RequestBody long id, HttpServletRequest request){
//        if (!isAdmin(request)){
//            return false;
//        }
        if (id <= 0){
            return false;
        }
        return userService.removeById(id);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

//    /**
//     * 是否位管理员
//     * @param request
//     * @return
//     */
//    private boolean isAdmin(HttpServletRequest request){
//        // 仅管理员可查询
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User user = (User) userObj;
//        return user != null && user.getUserRole() == ADMIN_ROLE;
//    }

}
